
import importlib
from pathlib import Path
from fastapi import FastAPI, APIRouter
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware


class GetRouters():
    def __init__(self, app:FastAPI):
        """
        自动生成路由配置，并添加到API中
            :param app: FastAPI 实例对象
        """
        self._app = app

    def set_routers(self):
        """
        获取routers目录下所有可导入的路由
            :param app: FastAPI对象
        """
        path = Path(f"{Path.cwd()}/routers")
        if path.exists() and path.is_dir():
            # 搜索 routers 目录下所有 py 文件
            for p in path.glob('*.py'):
                file_name = p.name
                if not file_name.startswith("_"):
                    # 导入 routers 目录下所有 非_ 作为起始文件名的模块
                    file_name_no_suffix = p.stem
                    try:
                        moudle = importlib.import_module(f'routers.{file_name_no_suffix}')
                    except ImportError:
                        continue
                    # 跳过设置不自动解析的文件
                    if getattr(moudle, "__no_router__", None):
                        continue
                    # 直接获取 router 变量
                    if hasattr(moudle, "router") and isinstance(router := getattr(moudle, "router"), APIRouter):
                        self._app.include_router(router, prefix=f"/v1/{file_name_no_suffix}",
                                                 tags=[f"{file_name_no_suffix.capitalize()}"])
                        continue
                    # 解析 __router__ 变量
                    elif hasattr(moudle, "__router__"):
                        router = getattr(moudle, "__router__")
                        if isinstance(router, str):
                            router = getattr(moudle, router)
                        if isinstance(router, APIRouter):
                            self._app.include_router(router, prefix=f"/v1/{file_name_no_suffix}",
                                                     tags=[f"{file_name_no_suffix.capitalize()}"])
                            continue
                    # 倒序解析模块下所有实例变量
                    for ins in dir(moudle)[::-1]:
                        if not ins.startswith("_") and not ins[0].isupper() and isinstance(
                                router := getattr(moudle, ins), APIRouter):
                            self._app.include_router(router, prefix=f"/v1/{file_name_no_suffix}",
                                                     tags=[f"{file_name_no_suffix.capitalize()}"])
                            break


    def mount_static_files(self):
        """
        挂载静态文件
        """
        self._app.mount("/static", StaticFiles(directory="static"), name="static")

    def set_cros(self):
        """
        添加 CORS 跨域访问
        """
        origins = [
            "*"
        ]
        self._app.add_middleware(
            CORSMiddleware,
            allow_origins=origins,
            allow_credentials=True,
            allow_methods=["*"],
            allow_headers=["*"],
        )


def create_router(app:FastAPI):
    """
    创建APP的路由相关信息
    :param app:
    :return:
    """
    router = GetRouters(app)
    router.set_cros()
    router.set_routers()
    router.mount_static_files()
